package com.zhupanlin.zhyl.order.controller.api;

import com.zhupanlin.zhyl.common.result.Result;
import com.zhupanlin.zhyl.order.service.PaymentService;
import com.zhupanlin.zhyl.order.service.WXService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/12/8 15:30
 */
@RestController
@RequestMapping("/api/order/weixin")
public class WXController {

    @Autowired
    private WXService wxService;

    @Autowired
    private PaymentService paymentService;

    // 生成微信支付扫描的二维码
    @GetMapping("createNative/{orderId}")
    public Result createNative(@PathVariable("orderId") Long orderId) {
        Map<String, Object> map = wxService.createNative(orderId);
        return Result.ok(map);
    }

    // 查询支付状态
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable("orderId") Long orderId) {
        // 调用微信接口实现支付状态查询
        Map<String, String> map = wxService.queryPayStatus(orderId);
        if (map == null) {
            return Result.fail().message("支付失败");
        }
        if ("SUCCESS".equals(map.get("trade_state"))) {
            // 更新订单状态
            String outTradeNo = map.get("out_trade_no");
            paymentService.paySuccess(outTradeNo, map);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }

}
